//
//  QGTabBar.m
//  QuanGou
//
//  Created by qqqq on 15/11/21.
//  Copyright © 2015年 DongYongFei. All rights reserved.
//

#import "QGTabBar.h"

@interface QGTabBar ()

@property (nonatomic, strong) UIButton *plusButton;
@end
@implementation QGTabBar

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupPlusButton];
    }
    return self;
}

- (void)setupPlusButton
{
    UIButton *plusButton = [[UIButton alloc] init];
    // 设置背景
    [plusButton setBackgroundImage:[UIImage imageNamed:@"post_normal"] forState:UIControlStateNormal];
    [plusButton setBackgroundImage:[UIImage imageNamed:@"post_normal"] forState:UIControlStateHighlighted];

    [plusButton addTarget:self action:@selector(plusClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:plusButton];
    self.plusButton = plusButton;
}

- (void)plusClick
{
    
    if ([self.tabBarDelegate respondsToSelector:@selector(tabBarDidClick:)]) {
        [self.tabBarDelegate tabBarDidClick:self];
    }
}


- (void)layoutSubviews
{
    [super layoutSubviews];

    [self setupPlusButtonFrame];
    
    [self setupAllTabBarButtonsFrame];
}

/**
 *  设置所有plusButton的frame
 */
- (void)setupPlusButtonFrame
{
    
    self.plusButton.frame = CGRectMake( 0, 0, self.plusButton.currentBackgroundImage.size.width + 5, self.plusButton.currentBackgroundImage.size.height + 5);
    self.plusButton.center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5 - 10);
}

/**
 *  设置所有tabbarButton的frame
 */
- (void)setupAllTabBarButtonsFrame
{
    int index = 0;
    

    for (UIView *tabBarButton in self.subviews) {

        if (![tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) continue;

        [self setupTabBarButtonFrame:tabBarButton atIndex:index];

        index++;
    }
}

/**
 *  设置某个按钮的frame
 *
 *  @param tabBarButton 需要设置的按钮
 *  @param index        按钮所在的索引
 */
- (void)setupTabBarButtonFrame:(UIView *)tabBarButton atIndex:(int)index
{
    // 计算button的尺寸
    CGFloat buttonW = self.frame.size.width / (self.items.count + 1);
    CGFloat buttonH = self.frame.size.height;
    

    if (index >= 2) {
        tabBarButton.frame = CGRectMake(buttonW * (index + 1), 0, buttonW, buttonH);
    } else {
        tabBarButton.frame = CGRectMake(buttonW * index, 0, buttonW, buttonH);
    }

}



@end
